package com.xungou.order.service.impl;

import com.sun.org.apache.xpath.internal.operations.Or;
import com.xungou.core.mvc.AbstractService;
import com.xungou.core.mvc.IDao;
import com.xungou.good.dao.IGood;
import com.xungou.good.pojo.Good;
import com.xungou.order.dao.IOrder;
import com.xungou.order.pojo.Order;
import com.xungou.order.service.IOrderService;
import com.xungou.ordergood.dao.IOrderGood;
import com.xungou.ordergood.pojo.OrderGood;
import com.xungou.receiver.dao.IReceiver;
import com.xungou.receiver.pojo.Receiver;
import com.xungou.receiver.service.IReceiverService;
import com.xungou.shoppingCart.dao.IShoppingCart;
import com.xungou.utils.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("orderService")
public class OrderServiceImpl extends AbstractService<Order> implements IOrderService {
    @Resource
    private IOrder iOrder;
    @Resource
    private IOrderGood iOrderGood;
    @Resource
    private IShoppingCart iShoppingCart;
    @Resource
    private IGood igood;

    @Override
    protected IDao<Order> getDao() {
        return iOrder;
    }

    @Override
    public Map<String, Object> addOrder(Map<String, String> params) {
        String[] shopIds = params.get("shopIds").split(";");
        String[] goodId = params.get("goodIds").split(";");
        int flag = 0;
        for (int j = 0; j < shopIds.length; j++) {
            params.put("shopId", shopIds[j]);
            params.put("goodIds", goodId[j]);
            Order order = new Order();
            order.setPlaceOrderUser(UserUtil.getCurrentUser().getId());//下单人
            order.setPlaceOrderTime(new Date());//下单时间
            order.setStatus(Order.STATUS_PLACE);//订单状态
            order.setShop(Integer.parseInt(params.get("shopId")));//商铺ID
            order.setReceiver(Integer.parseInt(params.get("receiverId")));//收货人ID
            Float sum = this.selectSumByGoodIds(params);
            order.setSum(sum);//订单总额
            flag += this.insertSelective(order);
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyymmddhhmmss");
            order.setCode(dateFormatter.format(new Date()) + order.getId());//编码
            this.updateByPrimaryKeySelective(order);


            List<Map<String, Object>> cartGoods = iShoppingCart.getShoppingCartByIds(params);
            OrderGood orderGood;
            Good good;
            good = new Good();
            for (int i = 0; i < cartGoods.size(); i++) {
                orderGood = new OrderGood();
                orderGood.setOrder(order.getId());
                orderGood.setSum(Float.parseFloat(cartGoods.get(i).get("sum") + ""));
                orderGood.setCount(Integer.parseInt(cartGoods.get(i).get("count") + ""));
                orderGood.setGood(Integer.parseInt(cartGoods.get(i).get("id") + ""));
                orderGood.setGoodPrice(Float.parseFloat(cartGoods.get(i).get("price") + ""));
                orderGood.setGoodName(cartGoods.get(i).get("name") + "");
                iOrderGood.insert(orderGood);
                int count = orderGood.getCount();
                int stock = Integer.parseInt(cartGoods.get(i).get("stock") + "");
                stock = stock - count;
                if (stock >= 0) {
                    good.setId(orderGood.getGood());
                    good.setStock(stock);
                    igood.updateByPrimaryKeySelective(good);
                } else {
                    throw new RuntimeException("订单中“" + orderGood.getGoodName() + "”的数量已超过库存，当前库存为" + cartGoods.get(i).get("stock"));
                }
            }
            params.put("ids", params.get("goodIds"));
            iShoppingCart.deleteByIds(params);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("flag", flag);
        return result;
    }

    @Override
    public Float selectSumByGoodIds(Map<String, String> params) {
        return iOrder.selectSumByGoodIds(params);
    }

    @Override
    public List<Map<String, Object>> list(Map<String, Object> params) {

        return iOrder.list(params);
    }

    @Override
    public Map<String, Object> cancelOrder(Map<String, String> params) {
        Order order = new Order();
        order.setId(Integer.parseInt(params.get("id")));
        order.setCancelReason(params.get("reason"));
        order.setCancelTime(new Date());
        String from = params.get("from");
        if("buyer".equals(from))
            order.setStatus(Order.STATUS_CANCEL_BY_USER);
        else if("seller".equals(from))
            order.setStatus(Order.STATUS_CANCEL_BY_SELLER);
        int flag = iOrder.updateByPrimaryKeySelective(order);
        Map<String,Object> result = new HashMap<String,Object>();
        result.put("flag",flag);
        return result;
    }

    @Override
    public Map<String, Object> confirmReceive(Map<String, String> params) {
        Order order = new Order();
        order.setId(Integer.parseInt(params.get("id")));
        order.setReceiveGoodsTime(new Date());
        order.setStatus(Order.STATUS_RECEIVE);
        int flag = iOrder.updateByPrimaryKeySelective(order);
        Map<String,Object> result = new HashMap<String,Object>();
        result.put("flag",flag);
        return result;
    }

    @Override
    public List<Map<String, Object>> goodList(Map<String, Object> params) {
        return iOrder.goodList(params);
    }

    @Override
    public Map<String, Object> deliverGood(Order order) {
        order.setDeliverGoodsTime(new Date());
        order.setStatus(Order.STATUS_DELIVER);
        int flag = iOrder.updateByPrimaryKeySelective(order);
        Map<String,Object> result = new HashMap<String,Object>();
        result.put("flag",flag);
        return result;
    }

    @Override
    public Map<String, Object> selectGoodForEvaluate(Map<String, Object> params) {
        return iOrder.selectGoodForEvaluate(params);
    }
}